#!/bin/bash
set -e

if [ -f "tmp.mac" ]
then
    echo "Cannot continue if old tmp.mac exists"
    exit
fi

if [ ! -f "$1" ]
then
    if [ "$1" = "" ]
    then
	echo "Usage: ./drawdetector scintillators/draw_detector_definition.mac"
	exit
    fi
    echo "File $1 does not exist"
    exit
fi

# Get detector macro file name
DETECTOR=`sed -n -e "/\/control\/execute/p" $1 | sed -e "s/^\/control\/execute\ //g"`
echo Detector definition: $DETECTOR
# determine z-shift necessary to center the scintillation crystal
SCINTTHICKNESS=`grep /detector/scintThickness $DETECTOR`
SCINTTHICKNESS=`echo $SCINTTHICKNESS | sed -e 's@^/detector/scintThickness\ \([.0-9]\+\)\ mm$@\1@g'`
echo Scintillator thickness: $SCINTTHICKNESS mm
SHELLTHICKNESS=`grep /detector/shellThickness $DETECTOR`
SHELLTHICKNESS=`echo $SHELLTHICKNESS | sed -e 's@^/detector/shellThickness\ \([.0-9]\+\)\ mm$@\1@g'`
echo Shell thickness: $SHELLTHICKNESS mm
AIRGAP=`grep /detector/airGap $DETECTOR`
AIRGAP=`echo $AIRGAP | sed -e 's@^/detector/airGap\ \([.0-9]\+\)\ mm$@\1@g'`
echo Air gap: $AIRGAP mm
SHIFT=`echo scale=3\;\($SCINTTHICKNESS+$SHELLTHICKNESS+$AIRGAP\)-20 | bc`
echo Shift: $SHIFT mm


echo /vis/open OGLSQt > tmp.mac
echo /vis/drawVolume >> tmp.mac
echo /vis/viewer/set/background 1. 1. 1. >> tmp.mac
echo /vis/viewer/set/style surface >> tmp.mac
echo /control/execute $1 >> tmp.mac
# add commands from printeps.mac and set target point
sed -e "s@\(/vis/viewer/set/targetPoint\ 0\ 0\ \)0\(\ mm\)@\1${SHIFT}\2@g" printeps.mac >> tmp.mac

./scintillate -v tmp.mac
epstopdf tmp_0.eps
pdfcrop --margins="-130 -130 -130 -130" tmp_0.pdf tmpout.pdf
mv tmpout.pdf ${1%\.*}.pdf

rm tmp.mac tmp_0.eps tmp_0.pdf
